//
//  RCCheckInModuleVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-9-24.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCCheckInModuleVC.h"
#import "IManager+RCCheckInRequest.h"
#import "GloableEngineService.h"
#import "RCCheckInModuleCell.h"
#import "CommonDefines.h"
#import "AppDelegate.h"
#import "RCMerchantDetailVC.h"
#import "RCLoginPageVC.h"
#import "RCMerchantListCell.h"

#define kSearchImageFile          @"image_search_searchBar.png"
#define kSearchIconImageFile      @"image_tabbar_search_normal.png"

#define kTextPlaceHolder          @"商户名，地址等..."

@interface RCCheckInModuleVC ()<IManagerDelegate,UITextFieldDelegate>{
    RCBaseListDataModel *_model;
    int64_t  _reqID;
    BOOL     _refresh;
    int      _pn;
    UITextField    *_searchTextField;
    BOOL    _searchMode;

    UITapGestureRecognizer *tap;
}
@property (nonatomic, retain) RCBaseListDataModel *model;
@property (nonatomic,retain) MBProgressHUDEx *progressHub;
@end

@implementation RCCheckInModuleVC
@synthesize model = _model;
@synthesize progressHub = _progressHub;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter]  addObserver:self
                                                  selector:@selector(refreshData) name:@"SelectCityChanged"
                                                    object:nil];
    }
    return self;
}


- (void) dealloc
{
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_reqID];
    [[NSNotificationCenter defaultCenter]  removeObserver:self
                                                     name:@"SelectCityChanged"
                                                   object:nil];
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    [_model release];
    [super dealloc];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.titleLabelText = @"选择商户";
    self.navigationItem.titleView = [self createTitleView];
    
    
    
    [self createSearchView];
    
	// Do any additional setup after loading the view.
    // 设置tableview相关参数
    if ( baseVCTableView != nil ) {
        self.view.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        //        baseVCTableView.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.backgroundColor = [UIColor clearColor];
        baseVCTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        baseVCTableView.frame = self.view.bounds;
        CGRect tableViewNewFrame = CGRectMake(baseVCTableView.frame.origin.x,baseVCTableView.frame.origin.y+45,baseVCTableView.frame.size.width,UIScreenHeight-20-self.navigationController.navigationBar.frame.size.height-4-49-45);
        baseVCTableView.frame = tableViewNewFrame;
        baseVCTableView.tableHeaderView = nil;
        baseVCTableView.tableFooterView = nil;
//        [self addPullRefresh];
    }
    
    [self refreshData];
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    
  
}
-(void) didTapOnTableView:(UIGestureRecognizer*) recognizer {
    if ([_searchTextField isFirstResponder]) {
        [self backBarButtonItemPressed:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) refreshData
{
    
    [_progressHub removeFromSuperview];
    [_progressHub release];
    _progressHub = nil;
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_reqID];

    
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    _refresh = YES;
    _pn = 0;
    
    
    NSString *cityID = [[GloableEngineService sharedInstance] selectedCityID];
    CLLocation *coor = [[GloableEngineService sharedInstance] locationInfo];
    NSString *lat = [NSString stringWithFormat:@"%lf",coor.coordinate.latitude];
    NSString *lng = [NSString stringWithFormat:@"%lf",coor.coordinate.longitude];

    
    if (_searchMode) {
        _reqID = [[IManager sharedInstance] requestCheckInShopList:cityID withShopName:_searchTextField.text withLat:lat withLng:lng withPn:_pn withRn:10 withDelegate:self];
    }else{
        _reqID = [[IManager sharedInstance] requestCheckInShopList:cityID withLat:lat withLng:lng withPn:_pn withRn:10 withDelegate:self];

    }
}


- (void) loadMoreData
{
    
    _refresh = NO;
    

    NSString *cityID = [[GloableEngineService sharedInstance] selectedCityID];
    CLLocation *coor = [[GloableEngineService sharedInstance] locationInfo];
    NSString *lat = [NSString stringWithFormat:@"%lf",coor.coordinate.latitude];
    NSString *lng = [NSString stringWithFormat:@"%lf",coor.coordinate.longitude];
    
    _reqID = [[IManager sharedInstance] requestCheckInShopList:cityID withLat:lat withLng:lng withPn:_pn withRn:10 withDelegate:self];
    
}



-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.model.listItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *cellID = @"RCMerchantListCell";
    RCMerchantListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[[RCMerchantListCell alloc] init] autorelease];
    }
    [cell bindData:[self.model.listItems objectAtIndex:[indexPath row]]];
    return cell;
    
//    RCCheckInModuleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RCCheckInModuleCell"];
//    if (cell == nil) {
//        cell =      [[[RCCheckInModuleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RCCheckInModuleCell"] autorelease];
//    }
//    RCCheckInItemDataModel *item = [self.model.listItems objectAtIndex:[indexPath row]];
//    [cell bindData:item];
//    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}



#pragma mark Imanager Delegate



- (void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    [_progressHub removeFromSuperview];
    [_progressHub release];
    _progressHub = nil;
    
    if (_reqID == requestId) {
        if (_refresh) {
            
            [self finishRefreshingData];
            _refresh = NO;
        }else{
            [self finishLoadMoreData];
        }
    }
    [RCAppDelegate alertWithCustomizeString:@"加载失败"];

}

- (void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    [_progressHub removeFromSuperview];
    [_progressHub release];
    _progressHub = nil;
    
    if (dataModel.errorNO == RCErrorTypeNoError) {
        RCBaseListDataModel *resultList = (RCBaseListDataModel *)dataModel;
        if (_refresh) {
          
            self.model = resultList;
//            [baseVCTableView reloadData];
            [self finishRefreshingData];
            _refresh = NO;
        }else{
            self.model.pn = resultList.pn;
            self.model.rn = resultList.rn;
            self.model.total = resultList.total;
            [self.model.listItems addObjectsFromArray:resultList.listItems];
            [baseVCTableView reloadData];
            [self finishLoadMoreData];
        }
        
        
        NSInteger currentTotal = [self.model.listItems count];
        _pn = currentTotal;
        
        if (currentTotal < self.model.total) {
            [self addPullLoadMore];
        }else{
            [self noMoreData];
        }
    }else{
        [RCAppDelegate alertWithCustomizeString:dataModel.errorMsg];
    }
    [baseVCTableView reloadData];
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 25)]autorelease];
    headerView.backgroundColor = [UIColor colorWithRed:194.0/255 green:194.0/255 blue:194.0/255 alpha:1];
    UILabel *t = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 200, 15)];
    [headerView addSubview:t];
    [t setTextColor:[UIColor whiteColor]];
    t.font = [UIFont fontWithName:kFontNameHelvetica size:12];
    t.backgroundColor = [UIColor clearColor];
    t.text = @"附近你可能想签到的商户";
    [t release];
    
    
    return headerView;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RCMerchant *item = [self.model.listItems objectAtIndex:[indexPath row]];
    RCMerchantDetailVC *vc = [[RCMerchantDetailVC alloc] initWithMerchantID:item.merchantID];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    [vc release];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

- (void) createSearchView
{
    UIImageView *searchImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 3, 310, 34)];
    searchImageView.userInteractionEnabled = YES;
    searchImageView.backgroundColor = [UIColor clearColor];
    NSString *searchpath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kSearchImageFile];
    [searchImageView setImage:[UIImage imageWithContentsOfFile:searchpath]];
    
    UIImageView *searchIconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 15, 16)];
    searchIconImageView.backgroundColor = [UIColor clearColor];
    NSString *searchIconpath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kSearchIconImageFile];
    [searchIconImageView setImage:[UIImage imageWithContentsOfFile:searchIconpath]];
    [searchImageView addSubview:searchIconImageView];
    [searchIconImageView release];
    
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 5, 280, 24)];
        _searchTextField.borderStyle = UITextBorderStyleNone;
        _searchTextField.delegate = self;
        _searchTextField.placeholder = kTextPlaceHolder;
        _searchTextField.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
        _searchTextField.textAlignment = UITextAlignmentLeft;
        _searchTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        _searchTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _searchTextField.returnKeyType = UIReturnKeySearch;
    }
    
    [searchImageView addSubview:_searchTextField];
    [searchImageView bringSubviewToFront:_searchTextField];
    
    [self.viewContainer addSubview:searchImageView];
    [searchImageView release];
}


- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField
{
    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapOnTableView:)];
    [baseVCTableView addGestureRecognizer:tap];
    [tap release];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if ([textField.text length] > 0) {
        _searchMode = YES;
        [_searchTextField resignFirstResponder];
        self.titleLabelText = @"商户查找";
        self.navigationItem.titleView = [self createTitleView];
        self.navigationItem.leftBarButtonItem = [self createBackBarButtonItem];
        [self refreshData];
        if (tap != nil) {
            [baseVCTableView removeGestureRecognizer:tap];
            tap = nil;
        }
        
    }else{
        [RCAppDelegate alertWithCustomizeString:@"请输入搜索关键字"];
    }
    
   
    return YES;
}


-(void) backBarButtonItemPressed:(id) sender {
    if (tap != nil) {
        [baseVCTableView removeGestureRecognizer:tap];
        tap = nil;
    }
    _searchMode = NO;
    [_searchTextField resignFirstResponder];
    self.titleLabelText = @"选择商户";
    self.navigationItem.titleView = [self createTitleView];
    self.navigationItem.leftBarButtonItem = nil;
    
    [self refreshData];
    
}



@end
